<?php

/**
 * @author: biggege
 * @since:  2021-09-17 19:59:46
 */
declare(strict_types = 1);

namespace App\Jobs;

use App\Http\Services\SubscribeMessageService;
use App\Models\SubscribeMessage;
use App\Repositories\Api\AdminRepository;
use App\Repositories\SubscribeMessageRepository;
use App\Repositories\MessageTemplateRepository;
use App\Repositories\WechatRepository;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;

use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

/**
 * Class SendWechat
 * @package App\Jobs
 */
class SendMessage implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    /**
     * @var int
     */
    private $messageId;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($messageId)
    {
        $this->messageId = $messageId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $message = (new SubscribeMessageRepository())->getOne($this->messageId);
        if (!$message) {
            Log::error(
                '[SendWechat] message is null',
                ['messages' => 'messageId:' . $this->messageId . ':' . json_encode(Request()->all())]
            );
            return false;
        }
        $msgData = $message->send_content;

        $wechat = new WechatRepository();
        $adminRepository = new AdminRepository();
        $contact = $adminRepository->getOne($message->admin_id);

        if (!$contact) {
            $e = new Exception('用户不存在');
            Log::error(
                '[SendWechat] decode error', [
                    'messages' => $e->getMessage() . '::' . json_encode(Request()->all()),
                    'code' => $e->getCode(),
                    'file' => $e->getFile(),
                    'line' => $e->getLine(),
            ]);
            return false;
        }

        $messageTemplateRepository = new MessageTemplateRepository();
        $template = $messageTemplateRepository->getOne($message->template_id);

        $messageService = new SubscribeMessageService();
        try {
            if (is_string($msgData)) {
                $msgData = json_decode($msgData, true);
            }

            $rs = $wechat->sendSubscribeMessage(
                $template->wx_template_id,
                $contact->open_id,
                $message->page,
                $msgData
            );

            $messageService->saveSendMessage($this->messageId, $wechat->sendData);

            if ($rs && $rs['errcode'] === 0) {
                $messageService->saveResultMessage($this->messageId, $rs, SubscribeMessage::STATUS_SUCCESS);
            } else {
                $messageService->saveResultMessage($this->messageId, $rs, SubscribeMessage::STATUS_FAIL);
            }

            return $rs;
            // 需要增加结果保存
        } catch (InvalidArgumentException|InvalidConfigException|GuzzleException $e) {
            Log::error(
                '[SendWechat] decode error', [
                    'messages' => $e->getMessage() . '::' . json_encode(Request()->all()),
                    'code' => $e->getCode(),
                    'file' => $e->getFile(),
                    'line' => $e->getLine(),
            ]);

            return false;
        }
    }
}
